package study.nosql.redis.service.key_event;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

/**
 * keyspace, 键空间通知
 * （1）监听的频道/通道是 __keyspace@当前库编号 __:操作key ，消息的内容是事件名称
 * （2）publish __keyspace@0__:_2_key set
 * （3）格式：_ _ keyspace @ * _ _ : *
 */
@Slf4j
//@Component
public class KeyspaceListener extends MessageListenerAdapter {

    private static final String PATTERN = "__keyspace@*__:*";

    private static final Topic TOPIC = new PatternTopic(PATTERN);

    public KeyspaceListener(RedisMessageListenerContainer container) {
        container.addMessageListener(this, TOPIC);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = StrUtil.str(message.getChannel(), "UTF-8");
        String opType = StrUtil.str(message.getBody(), "UTF-8");

        log.info(">>>>>> channel= {}, op_type= {}", channel, opType);
    }
}
